package com.veryon9.mobile.common;




import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;




import com.commonsware.cwac.endless.EndlessAdapter;
import com.veryon9.mobile.model.SlowForumDataSource;



import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.support.v4.view.Menu;
import android.support.v4.view.MenuItem;
import android.support.v4.view.Window;
import android.support.v4.view.MenuItem.OnMenuItemClickListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class On9GoldenActivity extends FragmentActivity {
    /** Called when the activity is first created. */
	private static int THEME = R.style.Theme_Sherlock;
	private static int menuItemId;
	private ArrayListFragment list = new ArrayListFragment();
	private static RotateAnimation rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
			1f, Animation.RELATIVE_TO_SELF,
			1f);

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(0, Menu.FIRST, 0, "Save")
		    .setIcon(R.drawable.ic_compose)
		    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		
		menu.add(0, Menu.FIRST + 1, 0, "Search")
	        .setIcon(R.drawable.ic_search)
	        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		
		MenuItem a = menu.add(0, Menu.FIRST + 2, 0, "Refresh")
	        .setIcon(R.drawable.ic_refresh)
	        .setOnMenuItemClickListener(new OnMenuItemClickListener(){
	        	public boolean onMenuItemClick(MenuItem arg0) {
	        		View mi = On9GoldenActivity.this.findViewById(menuItemId);
	        		mi.startAnimation(rotate);
	        		mi.setEnabled(false);
	        		
	        					list.reload();
	        					
	        	                return false;

	        	            }

	        	        });
	        	        
	        	        

	        a.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		
	        menuItemId = menu.getItem(2).getItemId();
		
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		for (String menuTitle : SlowForumDataSource.topicOptionsList)
		{
			menu.addSubMenu(0, Menu.FIRST, 0, menuTitle);
		}
		
		return super.onPrepareOptionsMenu(menu);
	}



	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(THEME);
		rotate.setDuration(600);
		rotate.setRepeatMode(Animation.RESTART);
		rotate.setRepeatCount(Animation.INFINITE);
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_ACTION_BAR);
	  if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
           
            getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();
        }
	}
	
	public static class ArrayListFragment extends ListFragment {

		SimpleAdapter adapter = null;
		
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
	  		new LoadItemsTask().execute();

				
        }
        
        public void reload()
        {
        	LoadItemsTask a = new LoadItemsTask();
        	a.execute();
        }

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
			Map<String, String> map = (Map<String, String>)l.getItemAtPosition(position);
			String threadUrl = map.get("LINK");
			String title = map.get("TITLE");
			Intent intent = new Intent();
			intent.setClass(this.getActivity(), ThreadContentActivity.class);
			intent.putExtra("CONTENT_LINK", threadUrl);
			intent.putExtra("TITLE", title);
			startActivity(intent);
            Log.i("FragmentList", "Item clicked: " + id);
        }
        
    	private class LoadItemsTask extends AsyncTask<Void, Void, Void>
    	{
		   private List<Map<String, String>> items;
		   
		   @Override
		   protected Void doInBackground(Void... params) {
		       	items = SlowForumDataSource.getTopicData();
		       	return null;
		   }
		   
		   @Override
		   protected void onPostExecute(Void result) {
		       	//adapter.setItems(items);
			   ForumEndlessAdapter adapter = new ForumEndlessAdapter(items);
				setListAdapter(adapter);
				View mi = ArrayListFragment.this.getActivity().findViewById(menuItemId);
				mi.clearAnimation();
				mi.setEnabled(true);
				ArrayListFragment.this.getActivity().invalidateOptionsMenu();
		   }
        }
    	
    	private class ForumEndlessAdapter extends EndlessAdapter {
    		
    		private List<Map<String, String>> storedItems = null;
    		private List<Map<String, String>> newItems = null;
    		
    		ForumEndlessAdapter(List<Map<String, String>> items) {
    			super(new SimpleAdapter(ArrayListFragment.this.getActivity(), items, R.layout.listitem, new String[] { "TITLE", "USERNAME", "LINK" }, 
    					new int[] {R.id.listitem_title, R.id.listitem_username,R.id.listitem_link }));
    		
    			storedItems = items;

    		}
    		
    		@Override
    		protected View getPendingView(ViewGroup parent) {
    			View row= getLayoutInflater(null).inflate(R.layout.listitem, null);
    			
    			View child=row.findViewById(R.id.listitem_title);
 			
    			child.setVisibility(View.GONE);
    			
    			child=row.findViewById(R.id.listitem_username);
    			
    			child.setVisibility(View.GONE);
    			
    			//child=ArrayListFragment.this.getActivity().findViewById(menuItemId);
    			//child.setVisibility(View.VISIBLE);
    			child.startAnimation(rotate);
    			
    			return(row);
    		}
    		
    		@Override
    		protected boolean cacheInBackground() {
    			//SystemClock.sleep(10000);				// pretend to do work
    			newItems = SlowForumDataSource.getTopicData();
    			return(getWrappedAdapter().getCount()<75);
    		}
    		
    		@Override
    		protected void appendCachedData() {
    			ArrayListFragment.this.getActivity().findViewById(menuItemId).startAnimation(rotate);
    			if (getWrappedAdapter().getCount()<75) {
    				SimpleAdapter wrap = (SimpleAdapter)getWrappedAdapter();
    				
    				for (Map<String, String> cItem : newItems)
    				{
    					storedItems.add(cItem);
    				}
    				wrap.notifyDataSetChanged();
    			}
    			ArrayListFragment.this.getActivity().findViewById(menuItemId).clearAnimation();
    		}
    	}
    	
    	
    }
	

	
	 
}